package cn.wangxl.group.rpc.protocol;

import cn.wangxl.group.rpc.rpcEntity.RpcRequest;
import cn.wangxl.group.rpc.rpcEntity.RpcResponse;
import com.alibaba.fastjson.JSON;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.*;

/**
 * @Deacription JavaMessageProtocol
 * @Author 20112128
 * @Date 2020/9/18 10:16
 **/
public class JavaMessageProtocol implements MessageProtocol{
    @Override
    public byte[] marshallingRequest(RpcRequest rpcRequest){

        try {
            return serialize(rpcRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public RpcRequest unmarshallingRequest(byte[] data) {
        try {
            return (RpcRequest)unSerialize(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public byte[] marshallingResponse(RpcResponse rpcResponse) {
        try {
            return serialize(rpcResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public RpcResponse unmarshallingResponse(byte[] data) {
        try {
            return (RpcResponse)unSerialize(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private byte[] serialize(Object object) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(baos);

        out.writeObject(object);
        return baos.toByteArray();
    }

    private Object unSerialize(byte[] data) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ObjectInputStream in = new ObjectInputStream(bais);

        Object object = null;
        try {
            object = in.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return object;
    }
}
